package services;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import util.Common;

import java.io.*;

import static util.ALiYun.ensureBucket;

/**
 * Created by Administrator on 2014/7/22.
 */
public class ALiYunService {






    private static String ALIYUN_ACCESS_KEY = Common.getStringConfig("aliyun.oss.access.key");
    private static String ALIYUN_SECRET_KEY = Common.getStringConfig("aliyun.oss.secret.key");
    private static String ALIYUN_ENDPOINT = Common.getStringConfig("aliyun.oss.endpoint");
    private static final long PART_SIZE = 5 * 1024 * 1024L; // 每个Part的大小，最小为5MB
    private static final int CONCURRENCIES = 2; // 上传Part的并发线程数。
    private static int BUFFER_SIZE = 4096;
    /*
    * 上传文件
    * */
    public static UploadResult upload(String bucketName,File file,String key){
        return upload(bucketName, "", file, key);
    }
    public static UploadResult upload(String bucketName,String folderName,File file,String key){
        try {
            OSSClient client = new OSSClient(ALIYUN_ENDPOINT,ALIYUN_ACCESS_KEY, ALIYUN_SECRET_KEY);
            ensureBucket(client, bucketName);
            // 使用multipart的方式上传文件
            InputStream content = null;
            content = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            meta.setContentLength(file.length());
            // 上传Object.
            PutObjectResult result = client.putObject(bucketName, folderName+key, content, meta);
            String imgurl = "http://" + bucketName + ".oss.aliyuncs.com/"+folderName+ key;
            content.close();
            return new UploadResult(true,imgurl);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new UploadResult(false,null,e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            return new UploadResult(false,null,e.toString());
        }
    }

    //上传文件结果类型
    public static class UploadResult{
        public String url;
        public String errorMsg;
        private Boolean isSuccess;
        UploadResult(Boolean result,String url ){
            this.isSuccess = result;
            this.url = url;
        }
        UploadResult(Boolean result,String url,String errorMsg ){
            this.isSuccess = result;
            this.url = url;
            this.errorMsg = errorMsg;
        }
        public Boolean isSuccess(){
            return this.isSuccess;
        }
    }

    //    根据URl获得存数数据的key
    public static String getKey(String url) {
        int index = url.lastIndexOf("/");
        return url.substring(index + 1, url.length());
    }
}


